package com.kai.service.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.kai.service.data.request.system.CreateRoleRequest;
import com.kai.service.data.request.system.UpdateRoleRequest;
import com.kai.service.data.response.system.RoleResponse;
import com.kai.service.enums.ResultCodeEnum;
import com.kai.service.enums.UserStatusEnum;
import com.kai.service.exception.GenericException;
import com.kai.service.system.entity.Role;
import com.kai.service.system.entity.RoleResource;
import com.kai.service.system.mapper.RoleMapper;
import com.kai.service.system.service.IRoleResourceService;
import com.kai.service.system.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kai.service.user.service.IUserRoleService;
import com.kai.service.user.service.IUserService;
import com.kai.service.user.entity.User;
import com.kai.service.user.entity.UserRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author wjk
 * @since 2021-11-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleResourceService roleResourceService;

    /**
     * 获取用户角色
     *
     * @param username
     * @return
     */
    @Override
    public List<RoleResponse> listUserRole(String username) {
        User user = userService.checkUserNotExist(username);
        List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, user.getId()));

        Set<Integer> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());

        if (CollectionUtil.isEmpty(roleIds)){
            return Lists.newArrayList();
        }

        List<Role> roleList = this.list(new LambdaQueryWrapper<Role>()
                .in(Role::getId, roleIds)
                .eq(Role::getStatus, UserStatusEnum.NORMAL.getCode()));
        
        return roleList.stream().map(role -> {
            RoleResponse roleResponse = new RoleResponse();
            BeanUtil.copyProperties(role, roleResponse);
            return roleResponse;
        }).collect(Collectors.toList());
    }

    /**
     * 获取所有角色列表
     *
     * @return
     */
    @Override
    public List<RoleResponse> listRole(String status) {
        List<RoleResponse> roleResponseList = new ArrayList<>();
        List<Role> roleList = this.list(new LambdaQueryWrapper<Role>().eq(StringUtils.isNotBlank(status), Role::getStatus, status));

        roleList.forEach(role -> {
            RoleResponse roleResponse = new RoleResponse();
            BeanUtil.copyProperties(role, roleResponse);
            roleResponseList.add(roleResponse);
        });
        return roleResponseList;
    }

    /**
     * 修改角色
     *
     * @param roleId
     * @param updateRoleRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean updateRole(Integer roleId, UpdateRoleRequest updateRoleRequest) {
        Date date = new Date();
        Role role = this.getById(roleId);
        if (null == role){
            throw new GenericException(ResultCodeEnum.ROLE_NOT_EXIST);
        }
        BeanUtil.copyProperties(updateRoleRequest, role);
        role.setId(roleId).setUpdateDatetime(date);
        this.updateById(role);

        // 修改角色权限
        roleResourceService.getBaseMapper().delete(new LambdaQueryWrapper<RoleResource>().eq(RoleResource::getRoleId, roleId));
        addRoleResource(roleId, updateRoleRequest.getResourceList());

        return true;
    }

    /**
     * 添加角色
     *
     * @param createRoleRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean createRole(CreateRoleRequest createRoleRequest) {
        Role one = this.getOne(new LambdaQueryWrapper<Role>().eq(Role::getSystemCode, createRoleRequest.getSystemCode()));
        if (null != one){
            throw new GenericException(ResultCodeEnum.ROLE_EXISTED);
        }

        Date nowDate = new Date();
        Role role = new Role();
        BeanUtil.copyProperties(createRoleRequest, role);
        role.setStatus(UserStatusEnum.NORMAL.getCode())
                .setCreateDatetime(nowDate)
                .setUpdateDatetime(nowDate);
        this.save(role);
        // 添加角色权限
        addRoleResource(role.getId(), createRoleRequest.getResourceList());

        return true;
    }

    /**
     * 切换角色启用状态
     *
     * @param roleId
     * @param status
     * @return
     */
    @Override
    public Boolean stateSwitch(Integer roleId, int status) {
        Role role = this.getById(roleId);
        if (null == role){
            throw new GenericException(ResultCodeEnum.ROLE_NOT_EXIST);
        }
        role.setStatus(status);
        return this.updateById(role);
    }

    /**
     * 添加角色权限
     *
     * @param roleId
     * @param resourceList
     */
    public void addRoleResource(Integer roleId, List<Integer> resourceList){
        List<RoleResource> roleResourceList = new ArrayList<>();
        resourceList.forEach(resourceId -> {
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(roleId).setResourceId(resourceId);
            roleResourceList.add(roleResource);
        });
        roleResourceService.saveBatch(roleResourceList);
    }

}
